// Author: Dr Hamid MADANI // // GET /api/record/audio/?ext=webm — stream the saved audio file. import { NextRequest, NextResponse } from 'next/server' import { createReadStream, statSync } from 'fs' import path from 'path' import { Readable } from 'stream' export const runtime = 'nodejs' export const dynamic = 'force-dynamic' const ROOT = path.join(process.cwd(), 'data', 'records') const SAFE = /^[a-zA-Z0-9_-]{1,128}$/ export async function GET( req: NextRequest, { params }: { params: Promise<{ sessionId: string }> }, ) { const { sessionId } = await params if (!SAFE.test(sessionId)) { return NextResponse.json({ error: 'invalid sessionId' }, { status: 400 }) } const ext = (req.nextUrl.searchParams.get('ext') === 'ogg' ? 'ogg' : 'webm') const fp = path.join(ROOT, `${sessionId}.${ext}`) let size: number try { size = statSync(fp).size } catch { return NextResponse.json({ error: 'not found' }, { status: 404 }) } const node = createReadStream(fp) // Convert Node Readable → Web ReadableStream for Next.js Response const web = Readable.toWeb(node) as unknown as ReadableStream return new NextResponse(web, { status: 200, headers: { 'Content-Type': ext === 'ogg' ? 'audio/ogg' : 'audio/webm', 'Content-Length': String(size), 'Cache-Control': 'no-store', }, }) }